﻿#include "SolutionWorker.h"
#include <QJsonDocument>
#include <SqliteDatabase.h>
#include <QThread>
#include <QSqlDatabase>

SolutionWorker::SolutionWorker(QString databaseType, QString databaseName, QObject *parent) : QObject(parent)
  ,m_tableName("solution")
  ,m_databaseType(databaseType)
  ,m_databaseName(databaseName)
{

}

SolutionWorker::~SolutionWorker()
{
    if(database!=nullptr){
        database->deleteLater();
        database = nullptr;
    }
}

void SolutionWorker::onInit()
{
    database = new SqliteDatabase(NULL,m_databaseName,m_tableName, m_databaseType);
}

QStringList SolutionWorker::readAllSolutionName()
{
    auto arr = database->readAllRows(m_tableName);
    QStringList namelist;
    for(int i=0;i<arr.size();++i){
        auto cur = arr[i].toObject();
        namelist<<cur["name"].toString();
    }
    return namelist;
}

bool SolutionWorker::renameSolution(const QString &oldName, const QString &newName)
{
    if(oldName == newName)
        return true;
    auto record = find(newName);
    if(!record.isEmpty())
        return false;
    auto jsonData = find(oldName);

    jsonData.insert("name",newName);

    return database->updateRow(m_tableName,jsonData["id"].toString(),jsonData);
}

QJsonObject SolutionWorker::find(const QString &name)
{
    QJsonObject jsonData;
    auto r = database->find(m_tableName,"\"name\":\""+name+"\"");
    if(!r.isEmpty())
        jsonData =  r.at(0).toObject();
    return jsonData;
}

QJsonObject SolutionWorker::readSolution(const QString& name)
{
    auto record = find(name);
    if(record.isEmpty()){
        SolutionEntity entity;
        entity.mName = name;
        database->createRow(m_tableName,entity.mId,QJsonDocument::fromVariant(entity.toVariant()).object());
    }

    record = find(name);
    return record["data"].toObject();
}

void SolutionWorker::updateSolution(const QString& name,const QJsonObject &data)
{
    auto record = find(name);
    if(record.isEmpty())
        return;

    record.insert("data",data);
    database->updateRow(m_tableName,record["id"].toString(),record);
}

bool SolutionWorker::deleteSolution(const QString &name)
{
    auto record = find(name);
    if(record.isEmpty()){
        return false;
    }
    return database->deleteRow(m_tableName,record["id"].toString());
}

bool SolutionWorker::createSolution(const QString &name, const QJsonObject &data)
{
    auto record = find(name);
    if(!record.isEmpty())
        return false;
    SolutionEntity entity;
    entity.mName = name;
    entity.mData = data;
    return database->createRow(m_tableName,entity.mId,QJsonDocument::fromVariant(entity.toVariant()).object());
}
